package com.boomkeeper.ftp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.boomkeeper.core.config.BaseConfig;
import com.boomkeeper.core.constant.Constant;

@Component
public class FtpService {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(FtpService.class);
	
	@Autowired
	private FtpHandler ftpHandler;
	
	@Autowired
	private BaseConfig baseConfig;
	
	private String lteDateVersion;
	
	private String lteDatePortalVersion;
	
	/**
	 * 上传版本到FTP
	 * @return 上传成功返回true，否则返回false
	 */
	public boolean uploadVersion() {
		boolean isSuccuss = false;
		
		if(this.checkFtpDir()) {
			isSuccuss = ftpHandler.upload(baseConfig.getLteVersion().getLteVersionPath(), this.lteDatePortalVersion);
		} else {
			LOGGER.error("FTP准备和检查工作失败");
		}
		
		return isSuccuss;
	}
	
	private boolean checkFtpDir() {
		boolean isSuccuss = false;
		this.lteDateVersion = Constant.FTP_BASE_PATH + baseConfig.getLteVersion().getDateVersion() + "-version/";
		this.lteDatePortalVersion = lteDateVersion + "Portal-version/";
		
		if (this.openFtpConnect()) {
			if (ftpHandler.isDirExist(lteDateVersion)) {
				if (!ftpHandler.isDirExist(lteDatePortalVersion)) {
					isSuccuss = this.ftpHandler.mkdir(lteDatePortalVersion);
				}
			} else {
				isSuccuss = this.ftpHandler.mkdir(lteDateVersion);
				isSuccuss = this.ftpHandler.mkdir(lteDatePortalVersion);
			}
		}
		
		return isSuccuss;
	}
	
	private boolean openFtpConnect() {
		String ip = baseConfig.getFtp().getIp();
		int port = baseConfig.getFtp().getPort();
		String username = baseConfig.getFtp().getUserName();
		String password = baseConfig.getFtp().getPassWord();
		
		return ftpHandler.connect(ip, username, password, port);
	}
}